import _ from 'lodash';

/**
 * 精度计算
 * @param {number} n1 数1
 * @param {number} n2 数2
 * @param {string} type 计算类型
 * @returns countNumber(0.1, 0.2, '+') === 0.3
 */
export const countNumber = (n1, n2, type = '+') => {
  let lintN1 = parseFloat(n1);
  let lintN2 = parseFloat(n2);
  if (isNaN(lintN1) || isNaN(lintN2)) return NaN;
  const dot1 = (lintN1.toString().split('.')[1] || '').length;
  const dot2 = (lintN2.toString().split('.')[1] || '').length;
  const maxDotLength = Math.max(dot1, dot2, 0);
  const pow = Math.pow(10, maxDotLength);
  const num1 = Math.round(lintN1 * pow);
  const num2 = Math.round(lintN2 * pow);
  switch (type) {
    case '/':
      return num1 / num2;
    case '*':
      return (num1 * num2) / (pow * pow);
    case '-':
      return (num1 - num2) / pow;
    case '+':
    default:
      return (num1 + num2) / pow;
  }
};

/**
 * 截取小数点后固定位数，不做四舍五入
 * @param {*} value
 * @param {*} precision 保留小数位数
 * @returns
 */
export const NumberFormat = (value, precision = 3) => {
  // 空返回'-'
  if (value === undefined || value === 'undefined' || value === null || value === 'null') {
    return '-';
  }
  if (isNaN(value)) {
    return '-';
  }
  return parseFloat(Number(value).toFixed(precision));
};
export const NumberFormat2 = (value, precision = 3) => {
  // 空返回'0'
  if (value === undefined || value === 'undefined' || value === null || value === 'null') {
    return '0';
  }
  if (isNaN(value)) {
    return '0';
  }
  return parseFloat(Number(value).toFixed(precision));
};
export const NumberSub = (value, precision = 3) => {
  // 不做四舍五入
  let regexp = new RegExp('^[-]?\\d+(?:\\.\\d{0,' + precision + '})?');
  return parseFloat((value + '').match(regexp));
};

/**
 * 解析url参数
 * @returns {object} url params
 */
export const getParamObj = () => {
  let url = window.location.href;
  let params = {};
  if (url.indexOf('?') > 0) {
    let baseUrl = url.substring(url.indexOf('?') + 1);
    baseUrl.split('&').map((x) => {
      let [k, v] = x.split('=');
      params[k] = v;
    });
  }
  return params;
};

/**
 * 交易中心新接口前端所需数据构建
 * @param {Array} power
 * @returns
 */
export const buildPower = (power = []) => {
  return _.flatten(
    power?.map((i) => {
      return i?.children?.map((j) => {
        j?.children?.forEach((k) => {
          k.children = [];
        });
        return { ...j, provinceId: i.value, provinceName: i.label };
      });
    }) || [],
  );
};

/**
 * 一维数组根据codes构建多维数组
 * @param {Array} codes
 * @param {Array} data
 * @returns
 */
export const getTreeByCodes = (codes = [], data = []) => {
  const allKeys = [];
  const fn = (opt, i) => {
    const code = codes[i];
    const options = [];
    const id = `${code}Id`;
    const name = `${code}Name`;
    const _opt = _.groupBy(opt, name);

    Object.keys(_opt).forEach((key) => {
      const k = _opt[key][0];
      const temp = {
        ...k,
        label: k[name],
        value: k[id],
      };
      if (code === 'group') {
        temp.key = `${code}_${_.uniqueId()}`;
      }
      if (i !== codes.length - 1) {
        const childOptions = _opt[key];
        temp.children = fn(childOptions, i + 1);
      } else {
        allKeys.push(k[id]);
      }

      options.push(temp);
    });

    return options;
  };

  return { treeOptions: fn(data, 0), allKeys };
};
